package com.zzsy.carosshopprojects.activitys.home.mainpage.orderamount;

import android.content.Context;

import com.king.base.util.ToastUtils;
import com.zzsy.carosshopprojects.base.BaseViewMode;
import com.zzsy.carosshopprojects.bean.BaseBean;
import com.zzsy.carosshopprojects.bean.OrderDetialBean;
import com.zzsy.carosshopprojects.bean.OrderDetialResultBean;
import com.zzsy.carosshopprojects.bean.RefundPasswordBean;
import com.zzsy.carosshopprojects.network.RequestUtils;
import com.zzsy.carosshopprojects.network.Utils.MyObserver;
import com.zzsy.carosshopprojects.util.AlgorithmUtil;
import com.zzsy.carosshopprojects.util.ConverterHelper;
import com.zzsy.carosshopprojects.util.DataUtil;
import com.zzsy.carosshopprojects.util.FormatTimeUtil;
import com.zzsy.carosshopprojects.util.StringUtils;
import com.zzsy.carosshopprojects.view.paypassdialog.PayPassDialog;
import com.zzsy.carosshopprojects.view.paypassdialog.PayPassView;

import java.math.BigDecimal;

import androidx.lifecycle.MutableLiveData;

public class OrderAmountDetailMode extends BaseViewMode {
    private MutableLiveData<OrderDetialResultBean> liveData;
    private MutableLiveData<Boolean> PwdData;
    private MutableLiveData<Boolean> dialogData;
    private String pwd = "";//退款密码
    private String orderId = "";
    private String orderNumbers = "";

    public MutableLiveData<OrderDetialResultBean> getLiveData() {
        if (liveData == null)
            liveData = new MutableLiveData<>();
        return liveData;
    }

    public MutableLiveData<Boolean> getPwdData() {
        if (PwdData == null)
            PwdData = new MutableLiveData<>();
        return PwdData;
    }

    public MutableLiveData<Boolean> getdialogData() {
        if (dialogData == null)
            dialogData = new MutableLiveData<>();
        return dialogData;
    }

    /**
     * 获取订单详情接口
     *
     * @param
     * @param orderNumber
     */
    public void getOrderDetail(Context mContext, String orderNumber) {
        RequestUtils.OrderDetail(mContext, orderNumber, new MyObserver<OrderDetialBean>(mContext, false) {
            @Override
            public void onSuccess(OrderDetialBean result) {
                orderId = result.getId();
                orderNumbers = result.getOrderNumber();
                OrderDetialResultBean orderDetialResultBean = new OrderDetialResultBean();
                orderDetialResultBean.setMemberId(result.getMemberId());
                orderDetialResultBean.setMemberInfoCardDTO(result.getMemberInfoCardDTO());
                orderDetialResultBean.setOrderNumber(result.getOrderNumber());
                orderDetialResultBean.setRealName(result.getRealName());
                orderDetialResultBean.setMemberRedPackedAmountDou(AlgorithmUtil.getAmount(result.getMemberRedPackedAmount(), 100));
                orderDetialResultBean.setOrderSource(result.getOrderSource());
                orderDetialResultBean.setTime(FormatTimeUtil.formatTimeStamp2DateStr(String.valueOf(result.getOrderCreateTime() / 1000), "yyyy-MM-dd HH:mm:ss"));
                orderDetialResultBean.setOrderAmountDou(AlgorithmUtil.getAmount(result.getOrderAmount() + "", 100));
                orderDetialResultBean.setPayAmountDou(AlgorithmUtil.getAmount(result.getPayAmount() + "", 100));
                orderDetialResultBean.setActivityReductionDou(AlgorithmUtil.getSubtractAmount(orderDetialResultBean.getOrderAmountDou(), orderDetialResultBean.getPayAmountDou()));
                orderDetialResultBean.setOilNum(result.getOilNum());
                orderDetialResultBean.setStoreName(result.getStoreName());
                orderDetialResultBean.setPayType(result.getPayType());
                orderDetialResultBean.setCarNumber(result.getCarNumber());
                orderDetialResultBean.setRedPackedAmount(result.getRedPackedAmount() + "");
                orderDetialResultBean.setPayRule(result.getPayRule());
                String payTypeStr = "";
                if (!StringUtils.isEmpty(result.getPayType())) {
                    if ("1".equals(result.getPayType())) {
                        payTypeStr = "支付宝支付";
                    } else if ("2".equals(result.getPayType())) {
                        payTypeStr = "微信支付";
                    } else if ("3".equals(result.getPayType())) {
                        payTypeStr = "银联支付";
                    } else if ("4".equals(result.getPayType())) {
                        payTypeStr = "余额支付";
                    }
                    orderDetialResultBean.setPayTypeStr(payTypeStr);
                }
                int invoiceStatus = result.getInvoiceStatus();
                String invoiceStr = "";
                if (invoiceStatus == 1) {
                    invoiceStr = "已开票";
                } else if (invoiceStatus == 0) {
                    invoiceStr = "未开票";
                } else if (invoiceStatus == 2) {
                    invoiceStr = "不可开";
                } else {
                    invoiceStr = "未开票";
                }
                orderDetialResultBean.setInvoiceStr(invoiceStr);
                /**
                 * 获取优惠券个数
                 * */
                String couponAmount = "";
                if (result.getCouponDTOs() != null && result.getCouponDTOs().size() > 0) {
                    int size = result.getCouponDTOs().size();
                    for (int i = 0; i < size; i++) {
                        int preAmount = result.getCouponDTOs().get(i).getPreAmount();
                        BigDecimal bigDecimal = ConverterHelper.toBigDecimal(preAmount).divide(ConverterHelper.toBigDecimal(100)).setScale(1, BigDecimal.ROUND_HALF_UP);
                        double amount = bigDecimal.doubleValue();
                        couponAmount += ",￥" + amount;
                    }
                    orderDetialResultBean.setCouponAmount(couponAmount);
                    orderDetialResultBean.setSize(size + "");
                }
                /**
                 * 获取加油升数
                 * */
                try {
                    double oilsPrices;
                    String oilPrice = result.getOilPrice();
                    if (!StringUtils.isEmpty(oilPrice)) {
                        BigDecimal bigDecimalAmount = ConverterHelper.toBigDecimal(oilPrice).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        oilsPrices = bigDecimalAmount.doubleValue();
                    } else {
                        oilsPrices = 0;
                    }
                    orderDetialResultBean.setOilsPrices(oilsPrices + "");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /**
                 * 获取加油升数
                 * */
                try {
                    String riseNew = result.getRise();
                    if (StringUtils.isEmpty(riseNew)) {
                        riseNew = "0";
                    }
                    orderDetialResultBean.setRiseNew(riseNew);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                double memberBlanceAmountsDou;
                String memberBlanceAmounts = result.getRechargeBalance();
                if (!StringUtils.isEmpty(memberBlanceAmounts)) {
                    memberBlanceAmountsDou = ConverterHelper.toBigDecimal(memberBlanceAmounts).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                } else {
                    memberBlanceAmountsDou = 0;
                }
                orderDetialResultBean.setMemberBlanceAmountsDou(memberBlanceAmountsDou + "");

                /**
                 * 新增设备号
                 * */
                String terminalNo = result.getTerminalNo();
                if (StringUtils.isEmpty(terminalNo)) {
                    terminalNo = "";
                }
                orderDetialResultBean.setTerminalNo(terminalNo);

                /**
                 * 是否显示油价 1 打 0 不打
                 * */
                String oilPriceSwitch = result.getOilPriceSwitch();
                if (StringUtils.isEmpty(oilPriceSwitch)) {
                    oilPriceSwitch = "1";
                }
                orderDetialResultBean.setOilPriceSwitch(oilPriceSwitch);

                /**
                 * 手机号和昵称显示
                 * */
                String phone = result.getPhone();
                if (StringUtils.isEmpty(phone)) {
                    phone = "";
                }
                orderDetialResultBean.setPhone(phone);

                String timeout = result.getTimeOutDate();
                if (StringUtils.isEmpty(timeout)) {
                    timeout = "";
                } else {
                    timeout = FormatTimeUtil.formatTimeStamp2DateStr(String.valueOf(Long.parseLong(timeout) / 1000), "yyyy-MM-dd");
                }
                orderDetialResultBean.setTimeout(timeout);

                /**
                 * 车牌号和认证车辆
                 * */
                String certificationTypeName = result.getCertificationTypeName();
                orderDetialResultBean.setCertificationTypeName(certificationTypeName);

                liveData.postValue(orderDetialResultBean);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                ToastUtils.showToast(mContext.getApplicationContext(), errorMsg);
            }
        });


    }

    public void getTokens(Context context) {
        getToken(context, token -> {
            VerificationPwd(context, token);
        });
    }

    /**
     * 退款密码验证
     *
     * @param context
     * @param token
     */
    public void VerificationPwd(Context context, String token) {
        RequestUtils.VerificationPwd(context, DataUtil.getInstance().getStoreId(), token, new MyObserver<RefundPasswordBean>(context) {
            @Override
            public void onSuccess(RefundPasswordBean bean) {
                if (bean != null && bean.getRefundPasswordStatus() != null && bean.getRefundPasswordStatus().equals("1")) {
                    pwd = bean.getRefundPassword() == null ? "" : bean.getRefundPassword();
                }

                PayPassDialog payPassDialog = new PayPassDialog(context);
                payPassDialog.getPayViewPass().setHintText("请输入密码");
                payPassDialog.getPayViewPass()
                        .setPayClickListener(new PayPassView.OnPayClickListener() {
                            @Override
                            public void onPassFinish(String passContent) {
                                if (passContent.equals(pwd)) {
                                    payPassDialog.dismiss();
                                    getTokensRefun(context);

                                } else {
                                    payPassDialog.getPayViewPass().cleanAllTv();
                                    ToastUtils.showToast(context.getApplicationContext(), "密码错误,请重新输入~");

                                }
                            }

                            @Override
                            public void onPayClose() {
                                payPassDialog.dismiss();
                            }

                            @Override
                            public void onPayForget() {

                            }
                        });

            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                ToastUtils.showToast(context.getApplicationContext(), errorMsg);
            }
        });
    }

    public void getTokensRefun(Context context) {
        getToken(context, token -> {
            dialogData.postValue(true);
            RefundOrder(context, token);
        });
    }

    /**
     * 退款
     */
    public void RefundOrder(Context context, String token) {
        RequestUtils.RefundOrder(context, orderId, orderNumbers, token, new MyObserver<BaseBean>(context, false) {
            @Override
            public void onSuccess(BaseBean baseBean) {
            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                dialogData.postValue(false);
                if (code == 200) {
                    PwdData.postValue(true);
                    ToastUtils.showToast(context.getApplicationContext(), "操作成功");
                } else {
                    ToastUtils.showToast(context.getApplicationContext(), errorMsg);
                }

            }
        });
    }
}
